package com.monitor.service;





import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.log.Logger;
import com.monitor.model.Log;
import com.monitor.utils.HttpRequest;
import com.monitor.utils.PropertyUtil;

/**
 * 警报类 负责处理需要通知管理员情况
 * 
 * @author HanChen
 *
 */
public class Alarm {
	private static Logger logger = Logger.getLogger(Alarm.class);

	/**
	 * 发送短信 type对应聚合上的短信模板 
	 * <p>3293 温度危险值报警</p>
	 * <p>3292节点未工作或数据异常 </p>
	 * <p>3289密码重置或修改</p>
	 * <p>3293 对应的value #temp#={温度值}</p>
	 * <p>3292 对应的value #datatime#={2015-05-03 19:15:30}</p>
	 * <p>3289 对应的vlaue #password#={password}</p>
	 * 
	 */
	public static void sendMessage(int type,String value) {
		PropertyUtil prop = new PropertyUtil("config.properties", "UTF-8");
		//http://v.juhe.cn/sms/send?mobile=手机号码&tpl_id=短信模板ID&tpl_value=%23code%23%3D654654&key=
		boolean secondAlarm = prop.getBoolean("secondAlarm");
		int secondSpace = prop.getInt("secondSpace");
		long secondLastTime = prop.getLong("secondLastTime");
		int firstTimes = prop.getInt("firstTimes");
		//先判断是不是二段报警
		if(secondAlarm){
			//是
			//判断当前时间是不是超出了二段报警设定的时间间隔
			long now = System.currentTimeMillis();
			if(secondLastTime != 0 && (now-secondLastTime > secondSpace*60*1000)){
				send(type, value, prop);
			}
		}else{
			//否
			if(firstTimes == 5){
				prop.set("secondAlarm", "true");
				prop.set("secondLastTime", String.valueOf(System.currentTimeMillis()));
				
			}else{
				firstTimes += firstTimes;
				prop.set("firstTimes", String.valueOf(firstTimes));
			}
			prop.store();
			send(type, value, prop);
			
		}
		

	}

	private static void send(int type, String value, PropertyUtil prop) {
		String phoneStr = prop.get("phone");
		if(phoneStr.trim().equals("")){
			Log.me.saveMsg("没有合适的手机号码用以发送报警短信");
			logger.info("没有合适的手机号码用以发送报警短信");
			return;
		}
		for (String phone : phoneStr.split(",",0)) {
			logger.debug("手机号："+phone);
			if(!phone.equals("")){
				String url = null;
				try {
					url = "http://v.juhe.cn/sms/send?key="+prop.get("appKey")+"&tpl_id="+String.valueOf(type)
							+"&tpl_value="+URLEncoder.encode(value, "utf-8");
					url += "&mobile="+phone;
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			
				HttpRequest httpRequest = HttpRequest.get(url);
				JSONObject json =JSONObject.parseObject(httpRequest.body());
				Log.me.saveMsg(json.getString("reason"));
				logger.info("短信状态："+json.getString("reason"));
			}else{
				Log.me.saveMsg("手机号有错误");
				logger.info("没有合适的手机号码用以发送报警短信");
			}
		}
	}
	
}
